﻿using Brilliant_see.Core.AbstractClass;
using Brilliant_see.Core.Interfaces;
using Brilliant_see.Core.Models;
using System.Diagnostics;
using System.Reflection;

namespace Brilliant_see.App.Services;

public class SearchService
{
    public List<MapSourceSelectItemModel> MapSources { get; set; } = new List<MapSourceSelectItemModel>();

    public SearchService()
    {
        LoadMapSource();
    }

    public Task SearchAsync(ICollection<Comic> comics, string keyWord) => Task.Run(() =>
    {
        comics.Clear();

        List<Task> tasks = new List<Task>();
        foreach (var x in MapSources)
        {
            if (x.IsSelected)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var enumerator = await x.MapSource.GetSearchEnumeratorAsync(keyWord);
                    while (enumerator.MoveNext())
                    {
                        lock (comics)
                        {
                            comics.Add(enumerator.Current);
                        }
                        Thread.Sleep(50);
                    }
                }));
            }
        }

        Task.WaitAll(tasks.ToArray());
    });

    private void LoadMapSource()
    {
        var assembile = Assembly.Load("Brilliant_see.MapSources");
        var types = assembile.GetTypes().Where(t => t.Namespace == "Brilliant_see.MapSources").ToList();
        foreach (var type in types)
        {
            if (type.GetInterface(nameof(IMapSource)) is not null)
            {
                IMapSource mapSource = (IMapSource)(Activator.CreateInstance(type) ?? throw new Exception("未存在空构造函数"));
                MapSources.Add(new MapSourceSelectItemModel(mapSource, true));
            }
        }
    }
}
